﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using PanasonicWarranty.Business;

namespace PanasonicWarranty.UI
{
    public partial class StaffManagement : BasePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
        }

        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindListStaff();
            pagingtop.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PageSize = Convert.ToInt32(ddlSortable_length.SelectedValue);
                pagingtop.CurrentPage  = 1;
                pagingtop.PageSize  = PageSize;
                pagingtop.PageDisplay = 6;
                BindStaffType();
                BindStaffLevel();
                BindUnit(CurUser.UnitID);
                BindListStaff();
                hdfAction.Value = "Add";
            }
        }

        private void BindStaffType()
        {
            drdStaffType.DataSource = DB.pepsi_StaffTypes.OrderBy(p => p.StaffTypeName);
            drdStaffType.DataValueField = "StaffTypeID";
            drdStaffType.DataTextField = "StaffTypeName";
            drdStaffType.DataBind();
        }

        private void BindStaffLevel()
        {
            for (int i = 1; i <= 12; i++)
                drdStaffLevel.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }

        private void BindUnit(Guid? unitID)
        {
            var dataSource = DB.pepsi_Units.Where(p => p.ID == unitID).OrderBy(p => p.Name);
            foreach (var item in dataSource)
            {
                drdUnit.Items.Add(new ListItem(item.Name, item.ID.ToString()));
                BindUnit(item.ID, Server.HtmlDecode("--"));
            }
        }

        private void BindUnit(Guid? unitID, string ident)
        {
            var dataSource = DB.pepsi_Units.Where(p => p.ParentID == unitID).OrderBy(p => p.Name);
            foreach (var item in dataSource)
            {
                drdUnit.Items.Add(new ListItem(ident + item.Name, item.ID.ToString()));
                BindUnit(item.ID, Server.HtmlDecode("&nbsp;&nbsp;&nbsp;") + ident);
            }
        }

        private void BindListStaff()
        {
            int? currentPage = pagingtop.CurrentPage;
            int? pageSize = pagingtop.PageSize;
            int? totalRecord = 0;
            rptStaff.DataSource = DB.sp_pepsi_StaffGetByUnit_Paging(CurUser.UnitID, currentPage, pageSize, ref totalRecord);
            pagingtop.TotalRecord  = totalRecord.Value;
            pagingtop.Visible = pagingtop.TotalPage > 1;
            rptStaff.DataBind();
        }

        protected void rptStaff_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                if (e.Item.DataItem != null)
                {
                    HtmlTableCell cell = (HtmlTableCell)e.Item.FindControl("tdPhoneNumber");
                    string phoneNumber = (e.Item.DataItem.GetType().GetProperty("PhoneNumber").GetValue(e.Item.DataItem, null) as string);
                    if (phoneNumber.Length > 0)
                    {
                        cell.InnerHtml = (new Regex(@":\d+").Replace(phoneNumber.Substring(1), "")).Replace(",", "<br/>");
                    }
                }
            }
            catch { }
        }

        protected void rptStaff_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                hdfStaffID.Value = e.CommandArgument.ToString();
                Guid staffID = new Guid(e.CommandArgument.ToString());
                switch (e.CommandName)
                {
                    case "Edit":
                        hdfAction.Value = "Edit";
                        pepsi_Staff editObj = DB.pepsi_Staffs.FirstOrDefault(p => p.StaffID == staffID);
                        if (editObj != null)
                        {
                            txtStaffCode.Text = editObj.StaffCode;
                            txtStaffName.Text = editObj.StaffName;
                            txtDOB.Text = editObj.DateOfBirth == null ? "" : editObj.DateOfBirth.Value.ToShortDateString();
                            drdGender.SelectedValue = editObj.Gender.ToString();
                            drdStaffLevel.SelectedValue = editObj.StaffLevel.ToString();
                            drdStaffType.SelectedValue = editObj.StaffTypeID.ToString();
                            drdUnit.SelectedValue = editObj.UnitID.ToString();
                            drdStatus.SelectedValue = editObj.Actived.ToString();
                            txtAddress.Text = editObj.Address;
                            string phoneNumber = DB.fn_getStaffPhoneList(staffID);
                            if (!string.IsNullOrEmpty(phoneNumber))
                            {
                                txtPhoneNumber.Text = new Regex(@":\d+").Replace(phoneNumber.Substring(1), "");
                            }
                        }
                        break;
                    case "Delete":
                        hdfAction.Value = "Delete";
                        pepsi_Staff deleteObj = DB.pepsi_Staffs.FirstOrDefault(p => p.StaffID == staffID);
                        if (deleteObj != null)
                        {
                            //Kiểm tra User
                            if (DB.pepsi_Users.Any(p => p.StaffID == deleteObj.StaffID))
                            {
                                throw new Exception("Cannot delete this staff because it's in user!");
                            }
                            //Xóa contact
                            var contacts = DB.pepsi_Contacts.Where(p => p.StaffID == deleteObj.StaffID);
                            if (contacts != null)
                                DB.pepsi_Contacts.DeleteAllOnSubmit(contacts);
                            DB.pepsi_Staffs.DeleteOnSubmit(deleteObj);
                            DB.SubmitChanges();
                            BindListStaff();
                        }
                        break;
                }
            }
            catch(Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"" + ex.Message + "\");", true);
            }
            finally
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "registerScript();", true);
            }
        }

        private void CheckFullInfo()
        {
            if (string.IsNullOrEmpty(txtStaffCode.Text.Trim()))
                throw new Exception("Staff code not allow null!");
            if (string.IsNullOrEmpty(txtStaffName.Text.Trim()))
                throw new Exception("Staff name not allow null!");
            if (string.IsNullOrEmpty(txtDOB.Text.Trim()))
                throw new Exception("Date of birth not allow null!");
            if(!txtDOB.Text.Trim().IsDateTime())
                throw new Exception("Date of birth is invalid!");
            if (string.IsNullOrEmpty(txtPhoneNumber.Text.Trim()))
                throw new Exception("Phone number not allow null!");
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                CheckFullInfo();
                pepsi_Staff objStaff = new pepsi_Staff(); ;
                if (hdfAction.Value == "Edit")
                {
                    objStaff = DB.pepsi_Staffs.FirstOrDefault(p => p.StaffID == new Guid(hdfStaffID.Value));
                }
                else if (hdfAction.Value == "Add")
                {
                    objStaff.CreateDate = DateTime.Now;
                    DB.pepsi_Staffs.InsertOnSubmit(objStaff);
                }
                //Check staff code
                if (pepsi_Staff.CheckExistsStaffCode(objStaff.StaffID, txtStaffCode.Text.Trim()))
                {
                    throw new Exception("Staff code is already exists!");
                }
                //Gán các thuộc tính
                objStaff.StaffCode = txtStaffCode.Text.Trim();
                objStaff.StaffName = txtStaffName.Text.ToNormalString();
                objStaff.DateOfBirth = Convert.ToDateTime(txtDOB.Text.Trim());
                objStaff.Gender = Convert.ToBoolean(drdGender.SelectedValue);
                objStaff.StaffTypeID = Convert.ToInt16(drdStaffType.SelectedValue);
                objStaff.StaffLevel = Convert.ToInt32(drdStaffLevel.SelectedValue);
                objStaff.UnitID = new Guid(drdUnit.SelectedValue);
                objStaff.Actived = Convert.ToBoolean(drdStatus.SelectedValue);
                objStaff.Address = txtAddress.Text;
                //Delete số điện thoại cũ
                var oldcontact = DB.pepsi_Contacts.Where(p => p.StaffID == objStaff.StaffID);
                if (oldcontact != null)
                    DB.pepsi_Contacts.DeleteAllOnSubmit(oldcontact);
                //Thêm lại số điện thoại
                short i = 0;
                string []phoneNumber = txtPhoneNumber.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (pepsi_Contact.CheckExistsPhoneNumber(objStaff.StaffID, phoneNumber))
                {
                    throw new Exception("Phone number is already exists!");
                }
                if (!pepsi_Contact.CheckValidPhoneNumber(phoneNumber))
                {
                    throw new Exception("Phone number is invalid!");
                }
                foreach (string item in phoneNumber)
                {
                    pepsi_Contact newcontact = new pepsi_Contact();
                    newcontact.pepsi_Staff = objStaff;
                    newcontact.PhoneNumber = item.ToNormalPhoneNumber();
                    newcontact.OperatorID = newcontact.GetOperatorID();
                    newcontact.Actived = true;
                    newcontact.Priority = (++i);
                    DB.pepsi_Contacts.InsertOnSubmit(newcontact);
                }
                //SubmitChanges
                DB.SubmitChanges();
                ResetControl();
                BindListStaff();
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"" + ex.Message + "\");", true);
            }
            finally
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "registerScript();", true);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            RedirectToPage(DefaultURL);
        }

        protected void lbtnAddNew_Click(object sender, EventArgs e)
        {
            ResetControl();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "registerScript();", true);
        }

        private void ResetControl()
        {
            hdfAction.Value = "Add";
            //Clear textbox
            txtStaffCode.Text = string.Empty;
            txtStaffName.Text = string.Empty;
            txtDOB.Text = string.Empty;
            txtAddress.Text = string.Empty;
            txtPhoneNumber.Text = string.Empty;
        }

        protected void tSortable_length_SelectedIndexChanged(object sender, EventArgs e)
        {
            PageSize = Convert.ToInt32(ddlSortable_length.SelectedValue);
            pagingtop.PageSize  = PageSize;
            BindListStaff();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "registerScript();", true);
        }
    }
}